package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author DingYiYuan
 * @description
 * @time 2021/3/9 16:39
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    //解析mapper，获取SQL语句信息
    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        //解析查询标签Sql
        List<Element> selectList = rootElement.selectNodes("//select");
        parseSqlPutMappedStatement(namespace, selectList);

        //解析新增标签Sql
        List<Element> insertList = rootElement.selectNodes("//insert");
        parseSqlPutMappedStatement(namespace, insertList);

        //解析更新标签Sql
        List<Element> updateList = rootElement.selectNodes("//update");
        parseSqlPutMappedStatement(namespace, updateList);

        //解析删除标签Sql
        List<Element> deleteList = rootElement.selectNodes("//delete");
        parseSqlPutMappedStatement(namespace, deleteList);

    }

    //解析SQL语句放入MappedStatement
    private void parseSqlPutMappedStatement(String namespace, List<Element> list) {
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sqlText);
            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }


}
